package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.*;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CourseCategoryService;
import com.xuecheng.content.service.TeachplanService;
import org.apache.http.nio.entity.NHttpEntityWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @description: 课程计划业务实现类
 * @params:
 * @return:
 * @author: ajie
 * @date: 2024/1/14 10:21
 */
@Service
public class TeachplanServiceImpl implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    CourseCategoryService courseCategoryService;
    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;


    /**
     * @description: 查询课程计划树型结构
     * @params: [courseId]
     * @return:
     * @author: ajie
     * @date: 2024/1/14 14:15
     */
    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    /**
     * @description: 课程计划创建或修改
     * @params: [saveTeachplanDto]
     * @return:
     * @author: ajie
     * @date: 2024/1/14 16:38
     */
    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        //通过课程计划id判断是新增还是修改
        Long teachplanId = saveTeachplanDto.getId();
        if (teachplanId == null) {
            //新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
//            //确定排序字段，找到它的同级结点个数，排序字段就是个数+1  select count(1) from teachplan where course_id = 117 and parentid = 268
//            Long courseId = saveTeachplanDto.getCourseId();
//            Long parentid = saveTeachplanDto.getParentid();
//            Integer teachplanCount = getTeachplanCount(courseId, parentid);
//            teachplan.setOrderby(teachplanCount + 1);

            //使用时间戳当排序字段
            teachplan.setOrderby(String.valueOf(System.currentTimeMillis()));

            teachplanMapper.insert(teachplan);

        } else {
            //修改
            Teachplan teachplan = teachplanMapper.selectById(teachplanId);
            //将参数复制到teachplan
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);

        }
    }

    /**
     * @description: 查询当前teachplan同级结点的个数
     * @params: [courseId, parentid]
     * @return:
     * @author: ajie
     * @date: 2024/1/14 17:20
     */
    private Integer getTeachplanCount(Long courseId, Long parentid) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentid);
        Integer teachplanCount = teachplanMapper.selectCount(queryWrapper);
        return teachplanCount;
    }


    /**
     * @description: 删除课程计划及媒资信息
     * @params: [teachplanId]
     * @return:
     * @author: ajie
     * @date: 2024/1/14 21:20
     */
    @Transactional
    @Override
    public void deleteTeachplanById(Long teachplanId) {
        //删除第一级别的大章节时要求大章节下边没有小章节时方可删除。
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan == null){
            XueChengPlusException.cast("课程计划信息不存在");
        }
        //判断当前父结点课程计划的父结点是否为0，为0则一级结点
        Long parentid = teachplan.getParentid();
        if (parentid == 0){
            //判断当前一级结点下是否有二级结点
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid,teachplan.getId())
                    .eq(Teachplan::getCourseId,teachplan.getCourseId());
            Integer count = teachplanMapper.selectCount(queryWrapper);
            //有子结点不允许删除
            if (count > 0){
                XueChengPlusException.cast("课程计划还有子级的信息，无法操作");
            }
//            //删除课程计划并更改排序
//            deleteWithOrderTeachplanById(teachplanId,teachplan);
            //删除课程计划信息
            teachplanMapper.deleteById(teachplanId);

        }else {
            //父结点不是0的都是二级结点
            //删除第二级别的小章节的同时需要将teachplan_media表关联的信息也删除。
//            //删除课程计划并更改排序
//            deleteWithOrderTeachplanById(teachplanId,teachplan);
            //删除课程计划信息
            teachplanMapper.deleteById(teachplanId);
            //删除绑媒资信息
            LambdaQueryWrapper<TeachplanMedia> mediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
            mediaLambdaQueryWrapper.eq(TeachplanMedia::getTeachplanId,teachplanId);
            teachplanMediaMapper.delete(mediaLambdaQueryWrapper);
        }

    }

    /**
     * @description: 删除课程计划并更改排序
     * @params: [teachplanId, teachplan]       
     * @return: 
     * @author: ajie
     * @date: 2024/1/15 13:40
     */
    public void deleteWithOrderTeachplanById(Long teachplanId,Teachplan teachplan){
        //删除课程计划信息
        teachplanMapper.deleteById(teachplanId);
        //查询排序字段，在它下面的课程计划全部上移一位
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        //同一父结点，并且大于当前排序的课程
        queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid())
                .eq(Teachplan::getCourseId,teachplan.getCourseId())
                .gt(Teachplan::getOrderby,teachplan.getOrderby());
        List<Teachplan> teachplanList = teachplanMapper.selectList(queryWrapper);
        teachplanList.forEach(item->{
            //item.setOrderby(item.getOrderby()-1);
            teachplanMapper.updateById(item);
        });

    }

    /**
     * @description: 课程计划向下移动 
     * @params: [id]       
     * @return: 
     * @author: ajie
     * @date: 2024/1/15 20:19
     */
    @Transactional
    @Override
    public void movedownTeachplan(Long id) {
        Teachplan teachplanOld = teachplanMapper.selectById(id);
        if (teachplanOld == null){
            XueChengPlusException.cast("当前课程计划不存在");
        }
        //获取相同父结点并且大于当排序的课程计划
        //SELECT * FROM `teachplan`
        //WHERE teachplan.parentid = 0 AND teachplan.course_id = 117 AND teachplan.orderby > 0
        //ORDER BY orderby
        //LIMIT 1
        Teachplan teachplanNew = teachplanMapper.queryGreaterOneById(teachplanOld);
        if (teachplanNew == null){
            XueChengPlusException.cast("已最后，无法移动");
        }
        //交换两个相邻的课程计划排序
        String temp=teachplanOld.getOrderby();;
        teachplanOld.setOrderby(teachplanNew.getOrderby());
        teachplanNew.setOrderby(temp);
        //更新
        teachplanMapper.updateById(teachplanOld);
        teachplanMapper.updateById(teachplanNew);


    }

    /**
     * @description: 课程计划向上移动
     * @params: [id]
     * @return:
     * @author: ajie
     * @date: 2024/1/15 22:11
     */
    @Override
    @Transactional
    public void moveupTeachplan(Long id) {
        Teachplan teachplanOld = teachplanMapper.selectById(id);
        if (teachplanOld == null){
            XueChengPlusException.cast("当前课程计划不存在");
        }
        //获取相同父结点并且大于当排序的课程计划
        //SELECT * FROM `teachplan`
        //WHERE teachplan.parentid = 268 AND teachplan.orderby < 5
        //ORDER BY orderby DESC
        //LIMIT 1
        Teachplan teachplanNew = teachplanMapper.queryLowerOneById(teachplanOld);
        if (teachplanNew == null){
            XueChengPlusException.cast("已最前，无法移动");
        }
        //交换两个相邻的课程计划排序
        String temp=teachplanOld.getOrderby();;
        teachplanOld.setOrderby(teachplanNew.getOrderby());
        teachplanNew.setOrderby(temp);
        //更新
        teachplanMapper.updateById(teachplanOld);
        teachplanMapper.updateById(teachplanNew);
    }

    /**
     * @description: 课程计划与媒资信息绑定
     * @params: [bindTeachplanMediaDto]
     * @return:
     * @author: ajie
     * @date: 2024/1/24 21:16
     */
    @Override
    @Transactional
    public void associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {

        //课程计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan == null){
            XueChengPlusException.cast("课程计划不存在");
        }

        //先删除原有记录，根据课程计划id删除它绑定的媒资
        int delete = teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, bindTeachplanMediaDto.getTeachplanId()));

        //再添加新纪录
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto,teachplanMedia);
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
    }

    /**
     * @description: 课程计划和媒资信息绑定
     * @params: [teachPlanId, mediaId]
     * @return:
     * @author: ajie
     * @date: 2024/1/24 22:07
     */
    @Override
    public void deleteAssociationMedia(Long teachPlanId, String mediaId) {
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,teachPlanId).eq(TeachplanMedia::getMediaId,mediaId);
        teachplanMediaMapper.delete(queryWrapper);
    }


}
